package com.atguigu.chapter08;

import com.atguigu.bean.AdsClickLog;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/16 15:08
 */
public class Flink03_High_Project_BlackList {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        WatermarkStrategy<AdsClickLog> wms = WatermarkStrategy
            .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner(new SerializableTimestampAssigner<AdsClickLog>() {
                @Override
                public long extractTimestamp(AdsClickLog element, long recordTimestamp) {
                    return element.getTimestamp() * 1000L;
                }
            });
        SingleOutputStreamOperator<String> main = env
            .readTextFile("input/AdClickLog.csv")
            .map(line -> {
                String[] datas = line.split(",");
                return new AdsClickLog(Long.parseLong(datas[0]),
                                       Long.parseLong(datas[1]),
                                       datas[2],
                                       datas[3],
                                       Long.valueOf(datas[4]));
            })
            .assignTimestampsAndWatermarks(wms)
            // 每个用户对每个广告的点击量
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
    
                private ValueState<Boolean> warnState;
                private ValueState<String> dateState;
                private ReducingState<Long> clickCountState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    clickCountState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Long>(
                        "clickCountState",
                        Long::sum,
                        Long.class
                    ));
    
                    warnState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("warnState", Boolean.class));
                    dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                }
                
                @Override
                public void processElement(AdsClickLog log,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 当进入第二天的时候, 应该清空状态, 点击量重新计算
                    // 重新启动后的第一条数据或者第二天的第一条数据
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    String today = df.format(new Date(log.getTimestamp() * 1000));
                    System.out.println(today);
    
                    if (dateState.value() == null || !today.equals(dateState.value())) {
                        clickCountState.clear();
                        warnState.clear();
    
                        dateState.update(today);
                    }
                    
                    
                    Long count = clickCountState.get();
                    
                    if (count == null || count < 100) {
                        clickCountState.add(1L);
                        count = clickCountState.get();
                        String msg = ctx.getCurrentKey() + "点击量是: " + count;
                        out.collect(msg);
                    } else if(warnState.value() == null){
                        // 把这个用户添加到黑名单, 不再统计这个用户的数据
                        String msg = ctx.getCurrentKey() + "点击量是: " + count + " 超出阈值, 加入黑名单";
                        ctx.output(new OutputTag<String>("black") {}, msg);
                        warnState.update(true);
                    }
                }
            });
        main.print("正常");
        main.getSideOutput(new OutputTag<String>("black") {}).print("黑名单");
        
        env.execute();
        
    }
}
